<!--
 * @Description: 知识考核题库
 * @Author: Boide
 * @Date: 2022-02-18 11:10:44
 * @LastEditors: guiyi@hongyi.tech
 * @LastEditTime: 2022-02-19 18:40:47
-->
<template>
  <el-card class="box-card">
    <el-form ref="queryForm" :model="query" :inline="true" label-width="0">
      <el-form-item label="" label-width="0">
        <el-input v-model.trim="query.content" placeholder="考核题目" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 100px;" v-model="query.type" clearable placeholder="全部类型" @change="tapQuestion">
          <el-option v-for="item in questionType" :key="item.id" :label="item.value" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 140px;" v-model="query.category" clearable placeholder="全部分类">
          <el-option v-for="item in categoryType"
            :key="item.key" :label="item.value" :value="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select style="width: 100px" v-model="query.status" clearable placeholder="全部">
          <el-option label="未发布" :value="0"></el-option>
          <el-option label="已发布" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button type="primary" v-has-permi="['/question/choiceQuestionDeleteBatch']" @click="handleDelete()">批量删除</el-button>
        <el-button type="primary" v-has-permi="['/question/publish/batch']" @click="handlePublish(1)">批量发布</el-button>
        <el-button type="primary" v-has-permi="['/question/publish/batch']" @click="handlePublish(0)">批量取消发布</el-button>
        <el-button type="primary" icon="el-icon-plus" v-has-permi="['/question/choiceQuestionAdd']" @click="handleAdd()">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="listLoading" :data="dataList" stripe border
      @selection-change="handleSelectionChange" row-key="questionId">
      <el-table-column type="selection" :selecttable="row => row.publishState===1" width="55" />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="考核题目" align="center" prop="content" />
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="分值" align="center" prop="score" />
      <el-table-column label="发布状态" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status===1">已发布</span>
          <span v-else>未发布</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
        <template slot-scope="{row}">
          <el-button v-has-permi="['/question/publish/batch']" type="text" @click="handlePublish(row.status===1?0:1,row.questionId)">
            <span v-if="row.status===1">取消发布</span>
            <span v-else>发布</span>
          </el-button>
          <el-button v-if="row.status!==1" v-has-permi="['/question/choiceQuestionDetail/*']" type="text" @click="handleAdd(row.questionId, true)">查看详情</el-button>
          <el-button v-if="row.status!==1" v-has-permi="['/question/choiceQuestionDetail/*', '/question/choiceQuestionEdit']" type="text" @click="handleAdd(row.questionId, false)">编辑</el-button>
          <el-button v-if="row.status!==1" v-has-permi="['/question/choiceQuestionDeleteBatch']" type="text" @click="handleDelete(row.questionId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize" @pagination="handleQuery" />

    <!-- 添加/修改考题 -->
    <el-dialog :title="(formModel.questionId?'编辑':'新增')+'考题'" :visible.sync="formVisible" width="888px" append-to-body>
      <el-form ref="formModel" :model="formModel" :rules="formModelRules" label-width="100px">
        <el-form-item label="考核题目:" prop="content">
          <el-input :readonly="editShow" v-model.trim="formModel.content" clearable placeholder="请输入题目" maxlength="50" />
        </el-form-item>
        <el-form-item label=" " v-if="(editShow&&formModel.questionImage)||!editShow">
          <upload-img :disabled="editShow" v-model="formModel.questionImage" />
        </el-form-item>
        <el-form-item label="类型-分类:" prop="quesCate">
          <el-cascader
            :disabled="editShow"
            :props="{
              value: 'key',
              label: 'value',
              children: 'questionCategories'
            }"
            v-model="formModel.quesCate"
            :options="questionType" />
        </el-form-item>
        <el-form-item label="分值:" prop="score">
          <el-input-number :disabled="editShow" v-model="formModel.score" controls-position="right" :min="1" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="" label-width="0" prop="questionOptions">
          <el-form-item label="答案列表:">
            <el-button v-if="!editShow" type="primary" @click="handleAnswerAdd()">添加答案</el-button>
          </el-form-item>
          <el-table :data="questionOptions" stripe border empty-text="未设置答案">
            <el-table-column label="序号" type="index" align="center" width="50" />
            <el-table-column label="答案内容" align="center" prop="content" />
            <el-table-column label="答案图片" align="center">
              <template slot-scope="{row}">
                <el-image
                  v-if="row.answerImage"
                  style="width: 80px; height: 80px"
                  :src="row.answerImage"
                  :preview-src-list="[row.answerImage]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="是否正确答案" align="center">
              <template slot-scope="{row}">
                <el-switch
                  :disabled="editShow"
                  v-model="row.isAnswer"
                  :inactive-value="0"
                  :active-value="1"
                />
              </template>
            </el-table-column>
            <el-table-column v-if="!editShow" label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="{row, $index}">
                <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/postUpdateWxTag']" type="text" @click="handleAnswerAdd(row, $index)">编辑</el-button>
                <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/postDelWxTag']" type="text" @click="handleAnswerDelete(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
        <el-button v-if="!editShow" :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加/修改答案 -->
    <el-dialog :title="(formAnswerModel.sort?'编辑':'新增')+'答案'" :visible.sync="formAnswerVisible" width="600px" append-to-body>
      <el-form ref="formAnswerModel" :model="formAnswerModel" :rules="formAnswerModelRules" label-width="100px">
        <el-form-item label="答案内容:" prop="content">
          <el-input :readonly="editShow" v-model.trim="formAnswerModel.content" clearable placeholder="请输入答案内容" maxlength="50" />
        </el-form-item>
        <el-form-item label=" " v-if="(editShow&&formAnswerModel.answerImage)||!editShow">
          <upload-img :disabled="editShow" v-model="formAnswerModel.answerImage" />
        </el-form-item>
        <el-form-item label="正确答案:" prop="type">
          <el-switch
            :disabled="editShow"
            v-model="formAnswerModel.isAnswer"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formAnswerVisible=!formAnswerVisible;resetAnswer;">取 消</el-button>
        <el-button type="primary" @click="submitAnswerForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { choiceQuestionList, choiceQuestionAdd, choiceQuestionEdit, choiceQuestionDetail,
 choiceQuestionDeleteBatch, getQuestionType, publishBatch } from '@/api/skinDisease/collocate/questionBank'

export default {
  name: "index",
  data () {
    const validatorQuestionOptions = (_, value, callback) => {
      if (this.questionOptions.length<=2) {
        callback(new Error('至少添加两项答案'));
      }
      let num = 0
      for (let i = 0; i < this.questionOptions.length; i++) {
        const o = this.questionOptions[i];
        if (o.isAnswer==1) {
          num += 1
        }
      }
      if (num<=0) {
        callback(new Error('至少要有一个正确答案'));
      }
      callback();
    }
    return {
      total: 0,
      questionType: [],
      categoryType: [],
      // 列表数据
      query: {
        pageNum: 1,
        pageSize: 10
      },
      dataList: [],
      listLoading: false,
      // 新增/编辑用户
      editShow: false,
      questionOptions: [],
      formVisible: false,
      submitLoading: false,
      formModel: {},
      formModelRules: {
        content: [
          { required: true, message: "考核题目不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "分值不能为空", trigger: "blur" }
        ],
        quesCate: [
          { required: true, message: "类型-分类不能为空", trigger: "blur" }
        ],
        questionOptions: [
          { required: true, validator: validatorQuestionOptions, trigger: "blur" }
        ]
      },
      // 答案
      answerIndex: 0,
      formAnswerVisible: false,
      formAnswerModel: {
        isAnswer: 0
      },
      formAnswerModelRules: {
        content: [
          { required: true, message: "答案内容不能为空", trigger: "blur" }
        ],
      },
      multipleSelection: []
    }
  },
  mounted () {
    this.getQuestionTypeFn()
    this.handleQuery()
  },
  methods: {
    // 获取分类数据
    getQuestionTypeFn() {
      getQuestionType().then(res => {
        this.questionType = res.data
      })
    },
    // 点击类型后的操作
    tapQuestion(e) {
      this.$set(this.query, 'category', '')
      this.questionType.forEach(o => {
        if (o.key === e) {
          this.categoryType = o.questionCategories
        }
      })
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val.map(o => o.questionId);
    },
    handleQuery () {
      this.listLoading = true
      let params = {...this.query}
      choiceQuestionList(params).then(res => {
        this.dataList = res.data.records
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    resetQuery () {
      this.query = {
        pageNum: 1,
        pageSize: 10
      }
      this.categoryType = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleAdd(questionId, editShow) {
      this.reset()
      if (questionId) {
        choiceQuestionDetail(questionId).then(({data}) => {
          this.questionOptions = data.questionOptions
          this.formModel = {
            ...data,
            quesCate: [data.type, data.category]
          }
        })
      }
      this.editShow = editShow
      this.formVisible = !this.formVisible
    },
    // 发布/取消，单个/批量删除
    handleDelete (questionId) {
      if (!questionId&&!this.multipleSelection.length) {
        this.$message.warning('至少选择一项')
        return
      }
      this.$confirm(`请确认是否要${questionId?'删除':'批量删除'}考题?`, { type: 'warning' }).then(() => {
        choiceQuestionDeleteBatch(questionId?[questionId]:this.multipleSelection).then(() => {
          this.$message.success('删除成功')
          if (!questionId) {
            this.multipleSelection = []
          }
          this.handleQuery()
        })
      })
    },
    // 发布/取消，单个/批量发布
    handlePublish (status, questionId) {
      console.log(status)
      if (!questionId&&!this.multipleSelection.length) {
        this.$message.warning('至少选择一项')
        return
      }
      this.$confirm(`请确认是否要${questionId?(status===1?'发布':'取消发布'):(status===1?'批量发布':'批量取消发布')}考题?`, { type: 'warning' }).then(() => {
        publishBatch({
          choiceQuestionIds: questionId?[questionId]:this.multipleSelection,
          status
        }).then(() => {
          this.$message.success(status===1?'发布成功':'取消发布成功')
          if (!questionId) {
            this.multipleSelection = []
          }
          this.handleQuery()
        })
      })
    },
    handleAnswerAdd(row, i) {
      if (this.editShow) return
      this.resetAnswer()
      if (row) {
        this.formAnswerModel = {...row}
        this.answerIndex = i
      }
      this.formAnswerVisible = !this.formAnswerVisible
    },
    // 删除答案
    handleAnswerDelete (i) {
      this.$confirm(`请确认是否要删除该答案?`, { type: 'warning' }).then(() => {
        this.questionOptions.splice(i, 1)
      })
    },
    // 添加答案
    submitAnswerForm() {
      this.$refs["formAnswerModel"].validate(async valid => {
        if (valid) {
          let params = {...this.formAnswerModel}
          try {
            if (params.sort) {
              this.$set(this.questionOptions, this.answerIndex, params)
            } else {
              this.questionOptions.push({
                ...params,
                sort: this.questionOptions.length?this.questionOptions[this.questionOptions.length-1].sort+1:1
              })
            }
            this.formAnswerVisible = !this.formAnswerVisible
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          let params = {...this.formModel}
          params.questionOptions = this.questionOptions
          params.type = params.quesCate[0]
          params.category = params.quesCate[1]
          try {
            if (params.questionId) {
              await choiceQuestionEdit(params)
              this.$message.success('修改成功')
            } else {
              await choiceQuestionAdd(params)
              this.$message.success('新增成功')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {}
      this.questionOptions = []
      this.resetForm("formModel")
    },
    // 表单重置
    resetAnswer () {
      this.formAnswerModel = {
        isAnswer: 0
      }
      this.resetForm("formAnswerModel")
    },
  },
}
</script>

<style scoped>
.dh {
  width: 0;
  height: 100px;
  background-color: #1c84c6;
  transition: all 1s;
}
.dh.show {
  width: 200px;
}
.dh.hide {
  width: 0;
}
</style>
